package com.blue.base.web.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.blue.base.web.bean.OssInfo;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 阿里云OSS工具类
 *
 * @author liulei
 * @version 1.0
 */
@AllArgsConstructor
public class AliYunOssUtil {

    private static final Logger logger = LoggerFactory.getLogger(AliYunOssUtil.class);

    /**
     * OSS bucket配置
     */
    private static final String DEFAULT_BUCKET = "gyt-driver-public";

    private OSSClient ossClient;

    /**
     * 上传文件[如果是文件替换，注意要先移除文件]
     */
    @SneakyThrows
    public OssInfo uploadFile(MultipartFile multipartFile, String rootPath, String module) {
        String ossKey = generateOSSKey(rootPath, module, multipartFile.getOriginalFilename());
        ossClient.putObject(DEFAULT_BUCKET, ossKey, multipartFile.getInputStream());
        String fileUrl = getFileUrl(ossKey);
        logger.info("新增阿里云附件:{}", fileUrl);
        return OssInfo.builder().key(ossKey).url(fileUrl).build();
    }

    /**
     * 移除文件
     */
    public void removeFile(String ossKey) {
        logger.info("移除阿里云附件:{}", ossKey);
        ossClient.deleteObject(DEFAULT_BUCKET, ossKey);
    }

    /**
     * 移除多个文件
     */
    public void removeFiles(List<String> ossKey) {
        logger.info("移除阿里云附件集合:{}", ossKey);
        ossClient.deleteObjects(new DeleteObjectsRequest(DEFAULT_BUCKET).withKeys(ossKey));
    }

    /**
     * 获取文件url
     */
    public String getFileUrl(String fileKey) {
        // 设置URL过期时间为1小时  3600* 1000
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(DEFAULT_BUCKET, fileKey, expiration);
        logger.info("获取阿里云附件地址： {} {}", fileKey, url);
        if (url != null) {
            //如果是阿里云内网访问地址，替换 -internal
            String result = url.toString();
            result = result.replace("-internal", "");
            return result;
        }
        return null;
    }

    /**
     * 生成OSS文件key
     */
    private String generateOSSKey(String rootPath, String module, String fileName) {
        String filePrefix = StringUtils.substringBeforeLast(fileName, ".");
        String fileSuffix = StringUtils.substringAfterLast(fileName, ".");
        return String.format("%s/%s/%s/%s", rootPath, module, fileSuffix, generateOssName(filePrefix, fileSuffix));
    }

    /**
     * 生成OSS文件名
     *
     * @param fileNamePre 文件名前缀
     * @return 生成新的文件名称
     */
    private String generateOssName(String fileNamePre, String suffix) {
        String fileNameSuf = StringUtils.join(UUID.randomUUID().toString(), System.currentTimeMillis());
        return StringUtils.join(fileNamePre, "_", DigestUtils.md5Hex(fileNameSuf), ".", suffix).toLowerCase();
    }
}
